
//@ts-ignore
const i18n = require('LanguageData');

export default class Util {
    static getBezier(duration, startPos, endPos) {
        let c1 = cc.v2(startPos.x, (endPos.y + startPos.y) / 2)
        let c2 = cc.v2((startPos.x + endPos.x) / 2, endPos.y)
        let bzIn = cc.bezierTo(duration, [c1, c2, endPos])
        return bzIn
    }

    static random(lower, upper) {
        if (lower == upper)
            return lower
        return Math.floor(Math.random() * (upper - lower + 1)) + lower
    }


    static convertToNewParent(node: cc.Node, newParent: cc.Node, careScale = false) {
        if (careScale) {
            // cc.log("old scale:%s", node.scale)
            node.scale = node.scale * (node.parent.scale / newParent.scale)
            // cc.log("node.parent.scale:%s newParent.scale:%s", node.parent.scale, newParent.scale)
        }
        let ptWorld = node.convertToWorldSpaceAR(cc.Vec2.ZERO)
        let ptLocal = newParent.convertToNodeSpaceAR(ptWorld)
        node.parent = newParent
        node.position = cc.v3(ptLocal)
    }

    static PrefixInteger(num, length) {
        if (num >= 100)
            return num
        return (Array(length).join('0') + num).slice(-length);
    }

    //获取节点的高度
    static getNodeRealHeight(node: cc.Node) {
        return node.getContentSize().height * node.scaleY
    }

    static getLanguageStr() {
        let lang = cc.sys.language
        return 'zh'
    }

    static changeLanuage(lang:string) {
        i18n.init(lang);
        i18n.updateSceneRenderers()
    }

    static getMulLangText(key:string) {
        return i18n.t(key)
    }

    //获取结点右边的位置
    static getRightX(node: cc.Node, space: number) {
        return node.x + node.getContentSize().width * (1 - node.anchorX) * node.scaleX + space
    }

    static secondToStr(second, haveHour) {
        let sec = Math.floor(second % 60)
        let min = Math.floor(second / 60) % 60
        if (!haveHour) {
            return Util.PrefixInteger(min, 2) + ":" + Util.PrefixInteger(sec, 2)
        }
        let hour = Math.floor(second / 3600)
        // cc.log("sec:%s min:%s hour:%s", sec, min, hour)
        return Util.PrefixInteger(hour, 2) + ":" + Util.PrefixInteger(min, 2) + ":" + Util.PrefixInteger(sec, 2)
    }

    /**
     * 
     * @param toNode 目标兄弟结点，不是其父结点
     * @param fromNode 拥有当前位置的结点
     */
    static getPostionOnSameParent(toNode: cc.Node, fromNode: cc.Node) {
        let worldPt = fromNode.convertToWorldSpaceAR(cc.Vec2.ZERO)
        let localPt = toNode.parent.convertToNodeSpaceAR(worldPt)
        return localPt
    }

    static getDistanceOfTwoNode(first: cc.Node, second: cc.Node) {
        let v1 = first.convertToWorldSpaceAR(cc.Vec2.ZERO)
        let v2 = second.convertToWorldSpaceAR(cc.Vec2.ZERO)
        return v1.sub(v2).mag()
    }

    /** */
    static getMoveDuration(distance: number, durationMax: number = 0.5, speed = 400) {
        let d1 = distance / speed
        if (d1 > durationMax) {
            d1 = durationMax
        }
        return d1
    }

    static getRollAction() {
        return cc.repeatForever(cc.sequence(cc.scaleTo(0.2, 1.03, 0.985), cc.scaleTo(0.2, 0.985, 1.03), cc.scaleTo(0.2, 1.0)))
    }

    static disableNodeButton(btn: cc.Node) {
        if (btn.getComponent(cc.Button)) {
            btn.getComponent(cc.Button).interactable = false
        }
    }


    static formatDate(date: Date, fmt) {
        var o = {
            "M+": date.getMonth() + 1, //月份 
            "d+": date.getDate(), //日 
            "h+": date.getHours(), //小时 
            "m+": date.getMinutes(), //分 
            "s+": date.getSeconds(), //秒 
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度 
            "S": date.getMilliseconds() //毫秒 
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }

    static g_uuid = null;
    static getOrGenerateUUID() {
        if (this.g_uuid != null) {
            return this.g_uuid;
        }
        let uuid: string = cc.sys.localStorage.getItem("uuid")
        if (uuid && uuid.length > 0) {
            this.g_uuid = uuid;
            return uuid
        }
        let rd = this.random(1, 9999)
        uuid = Util.formatDate(new Date(), "yyyyMMdd-hhmmss-") + this.PrefixInteger(rd, 4)
        cc.sys.localStorage.setItem('uuid', uuid)
        console.log("generateUUID:%s", uuid)
        this.g_uuid = uuid;
        return uuid
    }

    static isNodeHitTouch(node: cc.Node, e: cc.Event.EventTouch) {
        if (node == null)
            return false
        return node.getBoundingBoxToWorld().contains(e.getLocation());
    }

    static changeScene(name: string) {
        cc.director.loadScene(name);
        cc.director.on(cc.Director.EVENT_AFTER_SCENE_LAUNCH, () => {
            let cam = new cc.Node('CameraClearStencil')
            let c = cam.addComponent(cc.Camera)
            cc.Canvas.instance.node.addChild(cam)
            cam.groupIndex = 1
            c.clearFlags = cc.Camera.ClearFlags.DEPTH | cc.Camera.ClearFlags.STENCIL
            c.depth = 10
            c.cullingMask = 0
            cc.director.off(cc.Director.EVENT_AFTER_SCENE_LAUNCH);
        })
    }

    /**
     * 计算隔几天，会取绝对值
     * @param tsOld 毫秒
     * @param tsNew 
     */
    static dayMillSecond = 86400000;
    static getDayDiff(date1:Date, date2:Date) {
        date1.setHours(0);date1.setMinutes(0);date1.setSeconds(0);date1.setMilliseconds(0)
        date2.setHours(0);date2.setMinutes(0);date2.setSeconds(0);date2.setMilliseconds(0)
        var day1 = Math.floor(date1.getTime() / this.dayMillSecond);
        var day2 = Math.floor(date2.getTime() / this.dayMillSecond);
        return Math.abs(day1 - day2);
    }

    static stringFormat(str: string, ...args: Array<any>) {
        return str.replace(/{(\d+)}/gm, function (ms, p1) {
            return typeof (args[p1]) == 'undefined' ? ms : args[p1]
        });
    }
}
